package com.cindata.api

import grails.converters.JSON
import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.FromServer
import groovyx.net.http.OkHttpBuilder

//import groovyx.net.http.HTTPBuilder
import okhttp3.OkHttpClient
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Value

import java.util.concurrent.TimeUnit

import static groovyx.net.http.util.SslUtils.ignoreSslIssues

class SearchApiService implements InitializingBean
{

    static scope = "singleton"
    OkHttpBuilder http

    @Value('${searchApi.address}')
    String apiAddress
    @Value('${searchApi.communitySearch}')
    String communitySearchAPI

    /**
     * 查询小区
     * @param city
     * @param address
     * @param count
     * @return
     */
    def communitySearch(String city, String keyword, Integer count)
    {
        def result
        try
        {
            result = post1(communitySearchAPI, [city: city, keyword: keyword, count: count])
        }
        catch (Exception ex)
        {
            result = [code: 1,
                data: [],
                message: ex.getMessage()]
        }
        return result
    }

    @Override
    void afterPropertiesSet() throws Exception
    {
        http = OkHttpBuilder.configure {
            if (apiAddress.contains("https"))
            {
                ignoreSslIssues execution //TODO 该配置不能应用于服务器上
            }
            request.uri = apiAddress
            // request.headers["Cache-Control"] = ["no-cache"]
            client.clientCustomizer { OkHttpClient.Builder builder -> builder.connectTimeout(5, TimeUnit.SECONDS)
            }
        }
    }

    def post(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${url}"
                request.contentType = ContentType.JSON
                if (data)
                {
                    request.body = data
                }
                log.info("--------------------->准备API请求，地址：${request.uri.path}")
                log.info("--------------------->准备API请求，参数：${JsonOutput.toJson(request.body).toString()}")
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def mapStr(Map data)
    {
        def mapString = ""
        data.each {
            mapString += "&" + it.key + "=" + it.value
        }
        return mapString
    }

    def postStr(String url, Map data)
    {
        try
        {
            http.post {
                request.uri.path = "${url}"
                request.contentType = ContentType.TEXT
                def mapString = mapStr(data)
                if (data)
                {
                    request.body = mapString
                }
                log.info("--------------------->准备API请求，地址：${request.uri.path}")
                log.info("--------------------->准备API请求，参数：${mapString}")
                println "======================="
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    println request.contentType
                    println json.toString()
                    return json
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def post1(String url, Map data)
    {
        def params = ""
        try
        {
            http.post {
                request.uri.path = "${url}"
                request.uri.query = data
                request.contentType = ContentType.JSON
                log.info("--------------------->准备API请求，地址：${request.uri.path}")
                //  log.info("--------------------->准备API请求，参数：${JsonOutput.toJson(request.body).toString()}")
                log.info("--------------------->准备API请求，参数：${data}")
                response.parser("application/text")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return json
                }
                response.failure { resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }

    def get(String url, Map data)
    {
        try
        {
            http.get {
                request.uri.path = "${url}"
                request.contentType = ContentType.JSON
                response.parser("application/json")
                response.success { FromServer resp, json ->
                    println resp.statusCode
                    return JSON.parse(json.toString())
                }
                response.failure { FromServer resp ->
                    println resp.statusCode
                    throw new Exception("调用接口失败，" + resp.message)
                }
            }
        }
        catch (e)
        {
            log.error(e)
            throw new Exception(e.getMessage())
        }
    }
}
